<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-01-12 10:20:07
 * @Last Modified time: 2023-01-12 13:44:06
 */
namespace addon\wechat\services;

use frank\utils\helper\HttpHelper;
use addon\wechat\constants\ErrorCode;
use addon\wechat\services\BizDataCrypt;
use frank\exception\CommonException;
/**
 * 微信小程序开放接口
 * Class WeappOpenApiService
 */
class WeappOpenApiService  extends \frank\base\BaseService
{
	/**
	 * 小程序appid
	 */
	protected $appid;

	/**
	 * 小程序secret
	 */
	protected $secret;

	/**
	 * 接口地址
	 */
	protected $apiUrl;

	/**
	 * 调用方式
	 */
	protected $method;

	/**
	 * 参数
	 */
	protected $params;

	public function __construct(){
		$this->appid = sysconf('wechat_weapp_appid');
		$this->secret = sysconf('wechat_weapp_secret');
	}

	/**
	 * 登录凭证校验
	 */
	public function jscode2session(string $js_code){
		$this->params['js_code'] = $js_code;
		$this->params['grant_type'] = 'authorization_code';
		$this->apiUrl = 'https://api.weixin.qq.com/sns/jscode2session';
		$this->method = "GET";
		return $this->httpCurl(true);
	}


	public function httpCurl(bool $isSecret = false){
		$this->params['appid'] = $this->appid;
		$isSecret && $this->params['secret'] = $this->secret;
		if($this->method == 'GET'){
			$res = HttpHelper::httpGet($this->apiUrl.'?'.http_build_query($this->params));
		}else{
			$res = HttpHelper::httpPost($this->apiUrl);
		}
		$result = json_decode($res,true);
		return ErrorCode::get($result);
	}

}